<script setup lang="ts">
import { computed, defineEmits, defineProps, reactive } from 'vue';

import { StorageManager } from '@vben-core/shared/cache';

import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
} from 'element-plus';

import { userApi } from '#/api';
import { useUserStore } from '#/store';

const props = defineProps({
  visible: Boolean,
});

const emit = defineEmits(['update:visible', 'refreshProfile']);
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
});
const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});

const updateInfo = reactive({
  data: {
    username: storageManager.getItem('username'),
    institution: storageManager.getItem('institution'),
  },
});

const userStore = useUserStore();

// 关闭对话框
const closeDialog = () => {
  emit('update:visible', false);
};

// 编辑个人信息
const editProfile = () => {
  const requestData = {
    userId: storageManager.getItem('userId'),
    username: updateInfo.data.username,
    institution: updateInfo.data.institution,
  };

  userApi
    .updateUserInfo(requestData)
    .then((response: any) => {
      if (response) {
        storageManager.setItem('username', response.username);
        storageManager.setItem('institution', response.institution);
        userStore.loginUser.username = response.username;
        userStore.loginUser.institution = response.institution;

        ElMessage.success('更新成功');
        emit('refreshProfile'); // 通知父组件刷新数据
        closeDialog();
      } else {
        ElMessage.error('更新失败');
      }
    })
    .catch((error) => {
      console.error('编辑请求发生错误:', error);
      ElMessage.error('编辑请求发生错误，请重试！');
    });
};
</script>

<template>
  <div>
    <ElDialog
      v-model="dialogVisible"
      v-if="dialogVisible"
      draggable
      align-center
      destroy-on-close
      width="350px"
      @close="closeDialog"
    >
      <template #header>
        <div
          class="flex h-10 items-center justify-center text-lg font-bold text-gray-800 dark:text-gray-200"
        >
          {{ $t('page.profile.edit') }}
        </div>
      </template>
      <ElForm v-model="updateInfo.data" class="p-8">
        <ElFormItem :label="$t('page.profile.nameLabel')" prop="username">
          <ElInput v-model="updateInfo.data.username" clearable />
        </ElFormItem>
        <ElFormItem
          :label="$t('page.profile.institutionLabel')"
          prop="institution"
        >
          <ElInput v-model="updateInfo.data.institution" clearable />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="flex justify-center space-x-4">
          <ElButton type="primary" @click="editProfile">
            {{ $t('page.profile.save') }}
          </ElButton>
          <ElButton @click="closeDialog">
            {{ $t('page.profile.cancel') }}
          </ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>
